package com.ruoyi.demo.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.ruoyi.demo.mapper.TDemoMapper;
import com.ruoyi.demo.domain.TDemo;
import com.ruoyi.demo.service.ITDemoService;
import com.ruoyi.common.utils.YoushudaUtils;
import com.ruoyi.system.service.SubtabulationService;


/**
 * 测试DemoService业务层处理
 *
 * @author ZGL
 * @date 2024-09-30 14:12:25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TDemoServiceImpl extends ServiceImpl<TDemoMapper, TDemo> implements ITDemoService
{
    @Autowired
    private TDemoMapper tDemoMapper;

    /**
     * 子表相关处理类
     */
    @Autowired
    private SubtabulationService subtabulationService;


    /**
     * 新增测试Demo
     *
     * @param tDemo 测试Demo
     * @return 结果
     */
    @Override
    public int insertTDemo(TDemo tDemo)throws Exception
    {

        /**
         * 新增情况下，ID本应该为空，现值是用于标记子表数据
         */
        Long fkId = tDemo.getId();
        int count = tDemoMapper.insert(tDemo);
        return count;
    }

    /**
    * 修改数据
    * 将null值转换成""
    * @return
    * @throws Exception
    */
    public int update(TDemo data) throws Exception {

        data = (TDemo) YoushudaUtils.convertNullAttr(data);

        return tDemoMapper.update(data,
                new QueryWrapper<TDemo>().lambda()
                        .eq(TDemo::getId, data.getId())
        );
    }

    /**
     * 流程中表单数据处理
     * @param data
     * @return
     * @throws Exception
     */
    public Map<String,Object> dealData(Object data)throws Exception{

        TDemo tDemo = JSONObject.parseObject(JSONObject.toJSONString(data), TDemo.class);

        /**
         * 1。判断当前数据是否存在
         */
        if(tDemoMapper.selectById(tDemo.getId())!=null){
            tDemoMapper.updateById(tDemo);
        }else{
            insertTDemo(tDemo);
        }
        /**
        * 返回结果
        */
        Map<String,Object> result=new HashMap<>();
        result.put("tableName","t_demo");
        result.put("id", tDemo.getId());
        return result;

    }

    /**
     * 批量删除测试Demo
     *
     * @param ids 需要删除的测试DemoID
     * @return 结果
     */
    @Override
    public int deleteTDemoByIds(Long[] ids)throws Exception
    {
        /**
         * 删除子表数据
         */
        subtabulationService.delete("TDemo",tDemoMapper.selectBatchIds(Arrays.asList(ids)));
        /**
         * 删除主表数据
         */
        return tDemoMapper.deleteBatchIds(Arrays.asList(ids));
    }

}
